<template>
  <!-- 公共导入组件 -->
  <upload-excel :on-success="upload" />
</template>

<script>
import { importEmployees } from '@/api/employees'
export default {
  methods: {
    async upload(data) {
      // 数据转换
      const newData = data.results.map(user => {
        return this.zh2en(user)
      })
      // 发送请求
      await importEmployees(newData)
      // 提示用户
      this.$message.success('上传成功')
      // 跳转页面
      this.$router.back()
      // console.log(newData)
    },
    // 遍历每个key然后重写key
    zh2en(user) {
      const newuser = {}
      const dict = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      Object.keys(user).forEach(key => {
        const newKey = dict[key]
        let value = user[key]
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          value = new Date(this.formatDate(value, '/'))
        }
        // if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
        //   newuser[newKey] = new Date(this.formatDate(user[key], '/'))
        // } else {
        //   newuser[newKey] = user[key]
        // }
        newuser[newKey] = value
      })
      return newuser
    },
    // 五位数进行转换
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
